<?php


namespace app\tickets\controller;


use Aliyun\Api\Sms\Request\V20170525\SendSmsRequest;
use app\api\controller\Common;
use app\api\controller\Commondevice;
use app\api\controller\Test;
use Log;
use think\Db;
use think\Exception;

require_once ROOT_PATH."extend/wxpay/lib/WxPay.Api.php";
require_once ROOT_PATH."extend/wxpay/lib/WxPay.Notify.php";


class Notify extends \WxPayNotify
{

    //回调模拟
    public function notify1(){
        //执行业务逻辑
        $where['order_sn'] = "2021020500003";
        $order = Db::name("tickets_order")->where($where)->find();
        //查询订单详情
        $detail = Db::name("tickets_order_detail")->where(['order_id'=>$order['id']])->find();
        //应出票

        if($detail['type']>1){
            //获取实名认证头像
            $faceUrl = Db::name("admin_fans")->where(['id'=>$order['fans_id']])->value("faceUrl");
        }


        if($order['invoice_status']==1){
            //查询电子票批次
            $hairpin = Db::name("tickets_hairpin")->where(['type'=>2,'status'=>1])->order("id desc")->find();
            $invoice_count = 0;
            if(!empty($order['crew'])){
                $crew = json_decode($order['crew'],true);
                foreach ($crew as $k=>$v){
                    $invoice_count++;
                    //生成电子票
                    $no = $hairpin['sina'].date("d");
                    $token = $order['id'].$k;
                    $token = sprintf("%06d", $token);;
                    $no = $no.$token;
                    $showmd5 = md5($no);
                    $showmd5 = substr($showmd5, 0,6);
                    $no = $no.$showmd5;
                    $data['uniacid'] = $order['uniacid'];
                    $data['hairpin_id'] = $hairpin['id'];
                    $data['no'] = $no;
                    $data['status'] = $hairpin['status'];
                    $data['addtime'] = time();
                    $data['order_id'] = $order['id'];
                    $data['effectivetime'] = time();
                    Db::name("tickets_card")->insertGetId($data,true);
                    //绑定电子票
                    $listData['order_id'] = $order['id'];
                    $listData['tickets_id'] = $detail['tickets_id'];
                    $listData['effective_time'] = $detail['effective_time'];
                    $listData['end_time'] = $detail['end_time'];
                    $listData['type'] = $detail['type'];
                    $listData['signcode'] = $no;
                    $listData['status'] = 0;
                    $listData['addtime'] = time();
                    $listData['degree'] = $detail['degree'];
                    $listData['fans_id'] = $order['fans_id'];
                    $listData['name'] = empty($v['name'])?'':$v['name'];
                    $listData['mobile'] = empty($v['mobile'])?'':$v['mobile'];
                    $listData['IDcard'] = empty($v['IDcard'])?'':$v['IDcard'];
                    $listData['create_data'] = date("Y-m-d");
                    $listData['face'] = empty($v['face'])?'':$v['face'];
                    Db::name("tickets_list")->insertGetId($listData,true);
                    //像设备下发人员信息
                    $commonDevice = new Commondevice();
                    if(!empty($v['IDcard'])){
                        $cardAdd['cardNos'] = [$v['IDcard'],$no]; //$order['IDcard']
                    }else{
                        $cardAdd['cardNos'] = [$no];
                    }
                    if(!empty($faceUrl)){
                        $cardAdd['faceImageBase64'] = $faceUrl;
                    }
                    if(!empty($v['face'])){
                        $cardAdd['faceImageBase64'] = $v['face'];
                    }
                    $cardAdd['employeeNo'] = $no;
                    $cardAdd['personName'] = $v['name'];
                    $cardValue = $commonDevice->cardAdd($cardAdd);
                    if($cardValue!=true){
                        $data['invoice_status'] = 1;
                    }else{
                        $data['invoice_status'] = 2;
                    }
                }
            }
        }

        //更新订单支付状态
//        $where['order_sn'] = $result['out_trade_no'];
//        $data['out_trade_order_id'] = $result['transaction_id'];
        $data['pay_type'] = 1;
        $data['is_pay'] = 2;
        $data['status'] = 2;
        $data['invoice_count'] = $invoice_count;
        Db::name("tickets_order")->where($where)->update($data);


    }


    //发送短信
    public function sms($code,$phone){
        $current_date = date("Y-m-d");;
        //记录当天发送的数量
        $detail = Db::name("sms")->where(['phone'=>$phone,'current_date'=>$current_date])->find();
//        if($detail['count']>1){
//            throw new Exception("超出当天可发送的数量");
//        }
        if(empty($detail)){
            $data['phone'] = $phone;
            $data['current_date'] = $current_date;
            $data['count'] = 1;
            Db::name("sms")->insert($data);
        }else{
            Db::name("sms")->where(['phone'=>$phone,'current_date'=>$current_date])->setInc("count",1);
        }

        $common = new Common();
        require_once ROOT_PATH."extend/sms/api_sdk//vendor/autoload.php";//引入PHPExcel加载文件
        // 初始化SendSmsRequest实例用于设置发送短信的参数
        $request = new SendSmsRequest();
        //可选-启用https协议
        //$request->setProtocol("https");
        // 必填，设置短信接收号码
        $request->setPhoneNumbers($phone);
        // 必填，设置签名名称，应严格按"签名名称"填写，请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/sign
        $request->setSignName("鲸探");
        // 必填，设置模板CODE，应严格按"模板CODE"填写, 请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/template
        $request->setTemplateCode("SMS_190283810");
        // 可选，设置模板参数, 假如模板中存在变量需要替换则为必填项
        $request->setTemplateParam(json_encode(array(  // 短信模板中字段的值
            "code"=>$code,
        ), JSON_UNESCAPED_UNICODE));
        // 可选，设置流水号
        $request->setOutId("yourOutId");
        // 选填，上行短信扩展码（扩展码字段控制在7位或以下，无特殊需求用户请忽略此字段）
        $request->setSmsUpExtendCode("1234567");
        // 发起访问请求
        $acsResponse = $common->getAcsClient()->getAcsResponse($request);
        return $acsResponse;
    }


    //处理微信支付回调(调用设备接口)
    public function notify(){
        $testxml  = file_get_contents("php://input");
        $jsonxml = json_encode(simplexml_load_string($testxml, 'SimpleXMLElement', LIBXML_NOCDATA));
        $result = json_decode($jsonxml, true);//转成数组，
        if($result){
            //如果成功返回了
            $out_trade_no = $result['out_trade_no'];
            if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
                //执行业务逻辑
                $where['order_sn'] = $result['out_trade_no'];
                $order = Db::name("tickets_order")->where($where)->find();
                //查询订单详情
                $detail = Db::name("tickets_order_detail")->where(['order_id'=>$order['id']])->find();
                //应出票

                if($detail['type']>1){
                    //获取实名认证头像
                    $faceUrl = Db::name("admin_fans")->where(['id'=>$order['fans_id']])->value("faceUrl");
                }


                if($order['invoice_status']==1){
                    //查询电子票批次
                    $hairpin = Db::name("tickets_hairpin")->where(['type'=>2,'status'=>1])->order("id desc")->find();
                    $invoice_count = 0;
                    if(!empty($order['crew'])){
                        $crew = json_decode($order['crew'],true);
                        foreach ($crew as $k=>$v){
                            $invoice_count++;
                            //生成电子票
                            $no = $hairpin['sina'].date("d");
                            $token = $order['id'].$k;
                            $token = sprintf("%06d", $token);;
                            $no = $no.$token;
                            $showmd5 = md5($no);
                            $showmd5 = substr($showmd5, 0,6);
                            $no = $no.$showmd5;
                            $data['uniacid'] = $order['uniacid'];
                            $data['hairpin_id'] = $hairpin['id'];
                            $data['no'] = $no;
                            $data['status'] = $hairpin['status'];
                            $data['addtime'] = time();
                            $data['order_id'] = $order['id'];
                            $data['effectivetime'] = time();
                            Db::name("tickets_card")->insertGetId($data,true);
                            //绑定电子票

                            $listDetail = Db::name("tickets_list")->where(['order_id'=>$order['id']])->value("id");
                            if(empty($listDetail)){
                                $listData['order_id'] = $order['id'];
                                $listData['tickets_id'] = $detail['tickets_id'];
                                $listData['effective_time'] = $detail['effective_time'];
                                $listData['end_time'] = $detail['end_time'];
                                $listData['type'] = $detail['type'];
                                $listData['signcode'] = $no;
                                $listData['status'] = 0;
                                $listData['addtime'] = time();
                                $listData['degree'] = $detail['degree'];
                                $listData['fans_id'] = $order['fans_id'];
                                $listData['name'] = empty($v['name'])?'':$v['name'];
                                $listData['mobile'] = empty($v['mobile'])?'':$v['mobile'];
                                $listData['IDcard'] = empty($v['IDcard'])?'':$v['IDcard'];
                                $listData['create_data'] = date("Y-m-d");
                                $listData['face'] = empty($v['face'])?'':$v['face'];
                                Db::name("tickets_list")->insertGetId($listData,true);

                                //$this->sms(rand(100000,999999),$v['mobile']);

                                $nowtime = date("Y-m-d");
                                if($nowtime>=$detail['effective_time']){
                                    //像设备下发人员信息
                                    $commonDevice = new Test();
                                    $personsCreate['employeeNo'] = $no;
                                    if(!empty($v['IDcard'])){
                                        $cardNos = [$v['IDcard'],$no]; //$order['IDcard']
                                    }else{
                                        $cardNos = [$no];
                                    }
                                    $personsCreate['personName'] = empty($v['name'])?"欢迎光临":$v['name'];

                                    $startTime = date("Y-m-d\T00:00:01P",strtotime($detail['effective_time']));
                                    $endtTime = date("Y-m-d\T23:59:59P",strtotime($detail['end_time']));
                                    $personsCreate['validBeginTime'] = $startTime;
                                    $personsCreate['validEndTime'] = $endtTime;
                                    $cardValue = $commonDevice->cardAdd($personsCreate,$cardNos);


                                    if(!empty($faceUrl)){
                                        $personsCreate['faceImageBase64'] = $faceUrl;
                                        $cardValue = $commonDevice->personsUpdate($personsCreate);
                                    }
                                    if(!empty($v['face']) & $v['face']!='null'){
                                        $personsCreate['faceImageBase64'] = $v['face'];
                                        $cardValue = $commonDevice->personsUpdate($personsCreate);

                                    }
                                }
                            }
                            if(!empty($order['fans_id'])){
                                $data['invoice_status'] = 1;
                            }else{
                                $data['invoice_status'] = 2;
                            }
                        }

                    }
                }

                //更新订单支付状态
                $where['order_sn'] = $result['out_trade_no'];
                $data['out_trade_order_id'] = $result['transaction_id'];
                $data['pay_type'] = 1;
                $data['is_pay'] = 2;
                $data['status'] = 2;
                $data['invoice_count'] = $invoice_count;
                Db::name("tickets_order")->where($where)->update($data);
                echo 'SUCCESS';
                return true;
            }
        }
        return false;
    }

    /**
     * 生成加密算法
     * @return mixed
     * @author zhixuedong
     * @date 2021/1/29/029
     */
    public function createtoken(){
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        mt_srand(10000000*(double)microtime());
        for ($i = 0, $str = '', $lc = strlen($chars)-1; $i < 32; $i++){
            $str .= $chars[mt_rand(0, $lc)].rand(1000000, 9999999);
        }
        return $str;
    }

    function newtext($params){
        $myfile = fopen(__DIR__."/newfile.txt", "a") or die("Unable to open file!");//这个是在c盘根目录生成文件
        $txt = $params;//获取参数
        $b="";
        foreach($txt as $k=>$v){
            $b = $b ."[".$k."]=>".$v."\n";
        }
        fwrite($myfile, $b);//写入内容,可以写多次哦,不过没啥意义,因为你拼接好字符串,一次写入就行了
        fclose($myfile);//关闭该操作
    }


    function newtext1($params){
        $myfile = fopen(__DIR__."/newfile1.txt", "a") or die("Unable to open file!");//这个是在c盘根目录生成文件
        $txt = $params;//获取参数

        fwrite($myfile, $txt);//写入内容,可以写多次哦,不过没啥意义,因为你拼接好字符串,一次写入就行了
        fclose($myfile);//关闭该操作
    }
}